var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require('body-parser')
var fs = require('fs')
// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');

var app = express();
// 注册 body-parser 中间件
app.use(bodyParser({ extended: false }))
// app.use(bodyParser.urlencoded({ extended: false }));

// 1.0 初始化orm
const orm = require('orm')
app.use(
  orm.express('mysql://root:123456@127.0.0.1:3306/dtcmsdb4', {
    define: function(db, models, next) {
      next()
    }
  })
)



// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');

// app.use(logger('dev'));
// app.use(express.json());
// app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser());
// app.use(express.static(path.join(__dirname, 'public')));

// app.use('/', indexRouter);
// app.use('/users', usersRouter);




app.all('/api/*', (req, res, next) => {
  //设置允许跨域响应报文头
  //设置跨域
  //res.header("Access-Control-Allow-Origin", "*");
  //res.header("Access-Control-Allow-Headers", "X-Requested-With"); // X-Requested-With
  //res.header("Access-Control-Allow-Methods", "*");

  res.header('Access-Control-Allow-Origin', '*')
  // 设置服务器支持的所有头信息字段
  res.header(
    'Access-Control-Allow-Headers',
    'Content-Type,Content-Length, Authorization, Accept,X-Requested-With'
  )
  // 设置服务器支持的所有跨域请求的方法
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')

  res.setHeader('Content-Type', 'application/json;charset=utf-8')
  next()
})


const apiRoute = require('./routes/apiRoute.js')
app.use('/', apiRoute)
app.use(express.static(path.join(__dirname, 'public')))

app.listen(8082, () => {
   console.log('vue-cms的api服务已启动, :8082');
});

// error handler
// app.use(function(err, req, res, next) {
//   // set locals, only providing error in development
//   res.locals.message = err.message;
//   res.locals.error = req.app.get('env') === 'development' ? err : {};

//   // render the error page
//   res.status(err.status || 500);
//   res.render('error');
// });

// module.exports = app;
